<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\common\controller\Api;
use Endroid\QrCode\QrCode;
use think\Db;

/**
 * 首页接口
 */
class Goods extends Api
{
    protected $noNeedLogin = ['getGoodsCategory','getGoods','getGoodsEdit'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }
    public function getGoodsCategory(){
        $list = Db::name("goods_category")->select();
        foreach ($list as $k=>$v){
            $list[$k]['banner'] = cdnurl($v['banner'],true);
        }
        $this->success("商品分类",$list);
    }
    public function getGoods(){
        $label_id = $this->request->post("label_id");
        $where['id'] = ['>',0];
        $where['is_show'] = 1;
        if($label_id){
            $where['label_id'] = $label_id;
        }
        // 获取分页数据
        $list = Db::name("goods")->where($where)->order("weigh desc")->paginate()->toArray();
       // $list = $list->toArray();
       // var_dump($list);exit;
      //  var_dump($list['data']);
       foreach ($list['data'] as $k=>$v){
          // var_dump($v);exit;
            $list['data'][$k]['image'] =  cdnurl($v['image'], true);
        }
        // 将数据转化为数组
        //$list = $list->toArray();
        // 返回数据
        $this->success('商品列表', $list);
    }
    public function getGoodsEdit(){
        $id = $this->request->post("goods_id");
        $data = Db::name("goods")->where(['id'=>$id])->find();
        $data['image'] = cdnurl($data['image'], true);
        $this->success("商品详情",$data);
    }
    public function goodsOrderEdit(){
        $user = $this->auth->getUser();
        $id = $this->request->post("id");
        $data = Db::name("goods")->where(['id'=>$id])->field("id,name,image,price,merchant_user_id")->find();
        if(!$data){
            $this->error("数据有误");
        }
        /*$data['image']=cdnurl($data['image'],true);
        $coupon_where['use_begtime'] = ['<',time()];
        $coupon_where['use_endtime'] = ['>',time()];

        $user_coupon = Db::name("user_coupon")->where($coupon_where)->where(['user_id'=>$user->id,'money'=>['<=',$data['price']],'is_used'=>1,'number'=>['<=',$data['price']]])->order("number desc")->find();*/
        //echo Db::name("user_coupon")->getLastSql();
        $coupon_data =\app\common\model\User::userCouponUse($user->id,$data['price'],$data['merchant_user_id']);
        $data['coupon_money'] = $coupon_data['dk_money']??0;
        $data['pay_money'] = sprintf("%.2f", $data['price'] - $data['coupon_money']);

        $data['image'] = cdnurl($data['image'],true);
        $data['coupon_id'] = $coupon_data['ids']??"0";
        if($data['merchant_user_id'] > 0){
            $merchant_score = self::getMerchantScore($user->id,$data['merchant_user_id']);
        }else{
            $merchant_score = 0;
        }
        $data['course_score'] = sprintf("%.2f",$user->score + $merchant_score);
        $this->success("商品支付详情",$data);
    }

    public function goodsOrderAdd(){
        $user = $this->auth->getUser();
        $goods_id = $this->request->post("goods_id");
        $pay_type = $this->request->post("pay_type");
        $coupon_id = $this->request->post("coupon_id","0");
        $goods_data = Db::name("goods")->where(['id'=>$goods_id])->find();
        if(!$goods_data){
            $this->error("数据有误");
        }
        $pay_money = $goods_data['price'];
        $coupon_ids = "0";
        /* if($coupon_id != "0"){
             $coupon_where['use_begtime'] = ['<',time()];
             $coupon_where['use_endtime'] = ['>',time()];
             $coupon_where['id'] = ['in',$coupon_id];

             $user_coupon = Db::name("user_coupon")->where($coupon_where)->where(['user_id'=>$user->id,'is_used'=>1,'money'=>['<=',$goods_data['price']],'number'=>['<=',$goods_data['price']]])->find();
             if(!$user_coupon){
                 $this->error("优惠券数据有误");
             }

        }*/
        $coupon_data = \app\common\model\User::userCouponUse($user->id,$goods_data['price'],$goods_data['merchant_user_id']);

        $pay_money = $pay_money - $coupon_data['dk_money'];
        $coupon_ids = $coupon_data['ids'];

        $out_trade_no = date("YmdHis") . mt_rand(100000, 999999);
        $in_data['out_trade_no'] = $out_trade_no;
        $in_data['goods_id'] = $goods_id;
        $in_data['price'] = $goods_data['price'];
        $in_data['merchant_user_id'] = $goods_data['merchant_user_id'];
        $in_data['coupon_id'] = $coupon_id;
        if($coupon_id != '0'){
            $in_data['is_coupon'] = 1;
        }
        $in_data['money'] = $pay_money;
        $in_data['coupon_money'] = $coupon_data['dk_money'];
        $in_data['user_id'] = $user->id;
        $in_data['createtime'] = time();
        $in_status = Db::name("goods_order")->insertGetId($in_data);
        if($pay_type == 2){
            /*if($goods_data['merchant_user_id'] > 0){
                $merchant_score = self::getMerchantScore($user->id,$goods_data['merchant_user_id']);
            }else{
                $merchant_score = 0;
            }
            $all_score = sprintf("%.2f",$user->score + $merchant_score);
            if($all_score < $pay_money){
                $this->error("积分不足");
            }*/
            $merchant_score = self::getMerchantScore($user->id,$goods_data['merchant_user_id']);

            if($merchant_score < $pay_money){
                $sy = $pay_money - $merchant_score;
                if($user->score < $sy){
                    $this->error("积分不足");
                }
                \app\common\model\User::score(-$merchant_score, $this->auth->id, "购买".$goods_data['name']."消耗积分",1,$goods_data['merchant_user_id'],$in_status);
                \app\common\model\User::score(-$sy, $this->auth->id, "购买".$goods_data['name']."消耗积分",0,$goods_data['merchant_user_id'],$in_status);
            }else{

                \app\common\model\User::score(-$pay_money, $this->auth->id, "购买".$goods_data['name']."消耗积分",1,$goods_data['merchant_user_id'],$in_status);
            }
           // \app\common\model\User::score(-$pay_money, $this->auth->id, "购买".$goods_data['name']."商品消耗积分",0,$goods_data['merchant_user_id']);
            $merchant_user = Db::name("merchant")->where(['id'=>$goods_data['merchant_user_id']])->value("user_id");
            \app\common\model\User::score($pay_money, $merchant_user, "卖出商品".$goods_data['name']);
            Db::name("goods_order")->where(['id'=>$in_status])->update(['status'=>1,'type'=>2]);
            Db::name("user_coupon")->where(['id'=>['in',$coupon_ids]])->update(['is_used'=>2]);
            Db::name("goods")->where(['id'=>$goods_id])->setInc("sales");
            if(!$in_status){
                $this->error("购买失败");
            }
            $this->success("购买成功");
        }else{
            $type = "wechat";
            $notifyurl = $this->request->root(true) . '/addons/epay/index/goodsnotifyx/paytype/' . $type;
            $returnurl = $this->request->root(true) . '/addons/epay/index/remap/paytype/' . $type . '/out_trade_no/' . $out_trade_no;
            $info = get_addon_info('third');
            if (!$info || !$info['state']) {

                $this->error("请在后台安装第三方登录插件");
            }
            $response = Service::submitOrder($pay_money, $out_trade_no, $type, "订单支付", $notifyurl, $returnurl,'miniapp',$user->openid);
            $this->success($out_trade_no,$response);
        }

    }
    public function goodsOrderList(){
        $user = $this->auth->getUser();
        $list = Db::name("goods_order")->where(['user_id'=>$user->id,'status'=>['>',0]])->order("id desc")->paginate()->toArray();
        // $list = $list->toArray();
        // var_dump($list);exit;
        //  var_dump($list['data']);
        foreach ($list['data'] as $k=>$v){
            $course_data = Db::name("goods")->where(['id'=>$v['goods_id']])->find();
            // var_dump($v);exit;
            $list['data'][$k]['image'] =  cdnurl($course_data['image'], true);
            $list['data'][$k]['name'] =  $course_data['name'];
            $list['data'][$k]['pay_type'] =  $v['type'];
            $list['data'][$k]['pay_money'] =  $v['money'];
            $list['data'][$k]['createtime'] =  date('Y-m-d',$v['createtime']);
        }
        // 将数据转化为数组
        //$list = $list->toArray();
        // 返回数据
        $this->success('列表', $list);
    }
    public function goodsUserOrderEdit(){
        $user = $this->auth->getUser();
        $order_id = $this->request->post("order_id");
        $order_data = Db::name("goods_order")->field("goods_id,id,price,money pay_money,status,sum,out_trade_no,createtime,type")->where(['id'=>$order_id,'user_id'=>$user->id])->find();
        if(!$order_data){
            $this->error("数据有误");
        }
        $course_data = Db::name("goods")->where(['id'=>$order_data['goods_id']])->find();
        // var_dump($v);exit;
        $order_data['image'] =  cdnurl($course_data['image'], true);
        $order_data['name'] =  $course_data['name'];
        $order_data['pay_type'] =  $order_data['type'];
        $order_data['coupon_money'] =  $order_data['price'] - $order_data['pay_money'];
        $order_data['createtime'] =  date('Y-m-d',$order_data['createtime']);
        if($order_data['status'] == 1){
            // 创建二维码
            $url = Db::name("config")->where(['name'=>'url'])->value("value");
            $text = "/pages-merchant/order/cancelAfterGoods?id=".$order_data['id'];
            $qrCode = new QrCode($text);

// 设置图片尺寸
            $qrCode->setSize(300);

// 设置二维码颜色和背景颜色
            $qrCode->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0]);
            $qrCode->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]);

// 保存二维码到本地
            $filePath = ROOT_PATH.'/public/uploads/qrcode/'.date("Y-m-d").'/'.$order_data['id'].'qrcode.png';
            $filePath1 = '/uploads/qrcode/'.date("Y-m-d").'/'.$order_data['id'].'qrcode.png';
            $path ='/public/uploads/qrcode/'.date("Y-m-d").'/';
            if (!is_dir(ROOT_PATH.$path))
            {
                mkdir(ROOT_PATH.$path,0777,true);
            }
            $qrCode->writeFile($filePath);
            $order_data['image_url'] = $url.$filePath1;
        }else{
            $order_data['image_url'] = '';
        }

        $this->success("商品订单详情",$order_data);
    }

    /**
     * @param $user_id
     * @param $merchant_user_id
     * @return float|int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 核销
     */
    public function goodsOrderOff(){
        $goods_id = $this->request->post("order_id");
        $user = $this->auth->getUser();
        $goods_order_data = Db::name("goods_order")->where(['id'=>$goods_id])->find();
        //echo Db::name("course_order_pre")->getLastSql();
        if(!$goods_order_data){
            $this->error("数据有误");
        }
        if($goods_order_data['status'] != 1){
            $this->error("不符合核销条件");
        }


        $merchant_id = Db::name("merchant")->where(['user_id'=>$user->id])->whereOr(['examine_user_ids_str'=>['like',','.$user->id.',']])->column('id');
        //if($goods_order_data['merchant_user_id'] !== $merchant_id){
        if(!in_array($goods_order_data['merchant_user_id'],$merchant_id)){
            $this->error("您没有核销权限");
        }
        Db::name("goods_order")->where(['id'=>$goods_id])->update(['status'=>5]);
        $this->success("核销成功");
    }
    public static function getMerchantScore($user_id,$merchant_user_id){
        $list = Db::name("user_score_log")->where(['user_id'=>$user_id,'merchant_user_id'=>$merchant_user_id,'is_fixed'=>1])->select();
        $vlu = 0;
        if($list){
            foreach ($list as $k=>$v){
                if($v['before'] > $v['after']){
                    $vlu -= abs($v['score']);
                }else{
                    $vlu += abs($v['score']);
                }
            }
        }
        return $vlu;
    }

    /**
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 申请退款
     */
    public function orderRefund(){
        $user = $this->auth->getUser();
        $order_id = $this->request->post("order_id");
        $order_data = Db::name("goods_order")->where(['id'=>$order_id,'user_id'=>$user->id])->find();
        if(!$order_data){
            $this->error("数据有误");
        }
        $goods_cancel = Db::name("config")->where(['name'=>"goods_cancel"])->value("value");
        $s_j_t = time() - $order_data['createtime'];//实际间隔时间
        $j_j_t = $goods_cancel * 3600;//设置间隔时间
        if($j_j_t > $s_j_t){
            $this->error($goods_cancel."小时内不允许取消");
        }
        if($order_data['status'] > 1){
            $this->error("不符合退款条件");
        }
        $up_status = Db::name("goods_order")->where(['id'=>$order_id])->update(['status'=>3]);
        if($up_status){
            $this->success("申请成功");
        }else{
            $this->error("申请失败");
        }
    }
    public function goodsOrderOffedit()
    {
        $order_id = $this->request->post("order_id");
        $user = $this->auth->getUser();
        $goods_order_data = Db::name("goods_order")->where(['id' => $order_id])->field("merchant_user_id,id,goods_id,status,createtime,user_id")->find();
        if (!$goods_order_data) {
            $this->error("数据有误");
        }
        $merchant_id = Db::name("merchant")->where(['user_id'=>$user->id])->whereOr(['examine_user_ids_str'=>['like',','.$user->id.',']])->column('id');
        //if($goods_order_data['merchant_user_id'] !== $merchant_id){
        if(!in_array($goods_order_data['merchant_user_id'],$merchant_id)){
            $this->error("您没有核销权限");
        }
        if ($goods_order_data['status'] != 1) {
            $this->error("不符合核销条件");
        }
        $goods_data = Db::name("goods")->where(['id' => $goods_order_data['goods_id']])->find();
        $user_data = Db::name("user")->where(['id' => $goods_order_data['user_id']])->find();
        $course_data['image'] = cdnurl($goods_data['image'], true);
        $course_data['name'] = $goods_data['name'];
        $course_data['nickname'] = $user_data['nickname'];
        $course_data['mobile'] = $user_data['mobile'];
        $course_data['createtime'] = date('Y-m-d H:i:s',$goods_order_data['createtime']);
        $this->success("核销详情",$course_data);
    }
}
